package com.xp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xp.entity.User;
import com.xp.mapper.UserMapper;
import com.xp.service.UserService;
import com.xp.utils.Result;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户服务实现类
 * 
 * @author AI Assistant
 * @since 2024-01-01
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;

    /**
     * 分页查询用户列表
     */
    @Override
    public Result<IPage<User>> getUserPage(Page<User> page, String username, String email, Integer status) {
        try {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            if (StringUtils.hasText(username)) {
                queryWrapper.like(User::getUsername, username);
            }
            if (StringUtils.hasText(email)) {
                queryWrapper.like(User::getEmail, email);
            }
            if (status != null) {
                queryWrapper.eq(User::getStatus, status);
            }
            
            // 按创建时间倒序排列
            queryWrapper.orderByDesc(User::getCreateTime);
            
            IPage<User> userPage = userMapper.selectPage(page, queryWrapper);
            
            // 清除密码字段
            userPage.getRecords().forEach(user -> user.setPassword(null));
            
            return Result.success(userPage);
        } catch (Exception e) {
            log.error("分页查询用户列表失败", e);
            return Result.error("查询用户列表失败");
        }
    }

    /**
     * 获取所有启用的用户
     */
    @Override
    public Result<List<User>> getEnabledUsers() {
        try {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getStatus, 1);
            queryWrapper.orderByAsc(User::getUsername);
            
            List<User> users = userMapper.selectList(queryWrapper);
            
            // 清除密码字段
            users.forEach(user -> user.setPassword(null));
            
            return Result.success(users);
        } catch (Exception e) {
            log.error("获取启用用户列表失败", e);
            return Result.error("获取用户列表失败");
        }
    }

    /**
     * 根据ID获取用户详情
     */
    @Override
    public Result<User> getUserById(Long id) {
        try {
            User user = userMapper.selectById(id);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 清除密码字段
            user.setPassword(null);
            
            return Result.success(user);
        } catch (Exception e) {
            log.error("获取用户详情失败，用户ID: {}", id, e);
            return Result.error("获取用户详情失败");
        }
    }

    /**
     * 创建用户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> createUser(User user) {
        try {
            // 检查用户名是否已存在
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, user.getUsername());
            User existingUser = userMapper.selectOne(queryWrapper);
            if (existingUser != null) {
                return Result.error("用户名已存在");
            }
            
            // 检查邮箱是否已存在
            if (StringUtils.hasText(user.getEmail())) {
                queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(User::getEmail, user.getEmail());
                existingUser = userMapper.selectOne(queryWrapper);
                if (existingUser != null) {
                    return Result.error("邮箱已存在");
                }
            }
            
            // 加密密码
            if (StringUtils.hasText(user.getPassword())) {
                user.setPassword(passwordEncoder.encode(user.getPassword()));
            }
            
            // 设置默认值
            if (user.getStatus() == null) {
                user.setStatus(1); // 默认启用
            }
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            
            int result = userMapper.insert(user);
            if (result > 0) {
                return Result.success("用户创建成功");
            } else {
                return Result.error("用户创建失败");
            }
        } catch (Exception e) {
            log.error("创建用户失败", e);
            return Result.error("创建用户失败");
        }
    }

    /**
     * 更新用户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> updateUser(Long id, User user) {
        try {
            // 检查用户是否存在
            User existingUser = userMapper.selectById(id);
            if (existingUser == null) {
                return Result.error("用户不存在");
            }
            
            // 检查用户名是否已被其他用户使用
            if (StringUtils.hasText(user.getUsername()) && !user.getUsername().equals(existingUser.getUsername())) {
                LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(User::getUsername, user.getUsername());
                queryWrapper.ne(User::getId, id);
                User duplicateUser = userMapper.selectOne(queryWrapper);
                if (duplicateUser != null) {
                    return Result.error("用户名已存在");
                }
            }
            
            // 检查邮箱是否已被其他用户使用
            if (StringUtils.hasText(user.getEmail()) && !user.getEmail().equals(existingUser.getEmail())) {
                LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(User::getEmail, user.getEmail());
                queryWrapper.ne(User::getId, id);
                User duplicateUser = userMapper.selectOne(queryWrapper);
                if (duplicateUser != null) {
                    return Result.error("邮箱已存在");
                }
            }
            
            // 更新用户信息
            user.setId(id);
            user.setUpdateTime(LocalDateTime.now());
            
            // 如果提供了新密码，则加密
            if (StringUtils.hasText(user.getPassword())) {
                user.setPassword(passwordEncoder.encode(user.getPassword()));
            } else {
                // 不更新密码
                user.setPassword(null);
            }
            
            int result = userMapper.updateById(user);
            if (result > 0) {
                return Result.success("用户更新成功");
            } else {
                return Result.error("用户更新失败");
            }
        } catch (Exception e) {
            log.error("更新用户失败，用户ID: {}", id, e);
            return Result.error("更新用户失败");
        }
    }

    /**
     * 删除用户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> deleteUser(Long id) {
        try {
            // 检查用户是否存在
            User user = userMapper.selectById(id);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            int result = userMapper.deleteById(id);
            if (result > 0) {
                return Result.success("用户删除成功");
            } else {
                return Result.error("用户删除失败");
            }
        } catch (Exception e) {
            log.error("删除用户失败，用户ID: {}", id, e);
            return Result.error("删除用户失败");
        }
    }

    /**
     * 更新用户状态
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> updateUserStatus(Long id, Integer status) {
        try {
            // 检查用户是否存在
            User user = userMapper.selectById(id);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 更新状态
            user.setStatus(status);
            user.setUpdateTime(LocalDateTime.now());
            
            int result = userMapper.updateById(user);
            if (result > 0) {
                return Result.success("用户状态更新成功");
            } else {
                return Result.error("用户状态更新失败");
            }
        } catch (Exception e) {
            log.error("更新用户状态失败，用户ID: {}, 状态: {}", id, status, e);
            return Result.error("更新用户状态失败");
        }
    }
}